var dbConfig = require('../../util/dbconfig');
var salt = require("crypto-js"); //引入数据库密码加密
var vertoken = require('../../util/token_vertify.js'); //引入token验证模块
//iconfont(ok)
getIconfont = async (req, res) => {
	var sql = 'select * from icon';
	var sqlArr = [];
	var cb = async (err, data) => {
		if (err) {
			res.send({
				"text": "函数错误,getIconfont",
				"code": 500
			});
		} else {
			res.send({
				"data": data,
				"code": 200,
				"text": "icon获取成功"
			})
		}
	}

	dbConfig.sqlConnection(sql, sqlArr, cb)
}

salesThings = async (req, res) => {
	if (req.query.page >= 1) { //分页器查询数据库
		req.query.page = (req.query.page - 1) * req.query.size
	}
	var sql = `select * from things order by browsenum DESC LIMIT ${req.query.page},${req.query.size} `;
	var sqlArr = [];
	var cb = async (err, data) => {
		if (err) {
			res.send({
				"text": "字段信息丢失,salesThings",
				"code": 500
			});
		} else {
			res.send({
				"data": data,
				"code": 200,
				"text": "物品获取成功"
			})
		}
	}

	dbConfig.sqlConnection(sql, sqlArr, cb)
}
getDetail = async (req, res) => {
	var sql = `select * from things where id = ${req.query.id}`;
	var sqlArr = [];
	var cb = async (err, data) => {
		if (err) {
			res.send({
				"text": "参数错误,getDetail",
				"code": 500
			});
		} else {
			res.send({
				"data": data[0],
				"code": 200,
				"text": "物品获取成功"
			})
		}
	}

	dbConfig.sqlConnection(sql, sqlArr, cb)
}
login = async (req, res) => {
	var Id = req.body.userName;
	var Password = salt.MD5(req.body.passWord);
	var sql = `select user_Id from users where user_Id = "${Id}" and user_pw = '${Password}'`;
	var sqlArr = [];
	var cb = async (err, data) => {
		if (err) {
			res.status(500).send({
				text: '服务器错误,login'
			})
		} else {
			if (data.length == 0) {
				res.send({
					text: '登录失败',
					status: 403
				})
			} else {
				vertoken.setToken(Id, Password).then((data) => {
					res.send({
						token: "Bearer " + data,
						text: '登录成功',
						status: 200
					})
				})
			}
		}
	}
	dbConfig.sqlConnection(sql, sqlArr, cb);
};
module.exports = {
	getIconfont,
	salesThings,
	getDetail,
	login
}
